package org.jeecgframework.web.controller;

import com.mybatis.ext.WiseCoreService;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.CbsEquipmentApplyServiceI;
import org.jeecgframework.web.service.CbsServiceAssignListServiceI;
import org.jeecgframework.web.service.CbsServiceServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.SimpleMailReceiver;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 备件申请单
 * @date 2018-01-31 11:45:33
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsEquipmentApplyController")
public class CbsEquipmentApplyController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsEquipmentApplyController.class);
    @Autowired
    private CbsEquipmentApplyServiceI cbsEquipmentApplyService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CbsServiceAssignListServiceI cbsServiceAssignListService;
    @Autowired
    private CbsServiceServiceI cbsServiceService;
    @Autowired
    private WiseCoreService wiseCoreService;
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 备件申请单列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsEquipmentApply")
    public ModelAndView cbsEquipmentApply(HttpServletRequest request) {
        String type = request.getParameter("type");
        request.setAttribute("type", type);
        return new ModelAndView("com/zybk/cbsequipmentapply/cbsEquipmentApplyList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsEquipmentApplyEntity cbsEquipmentApply, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsEquipmentApplyEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsEquipmentApply, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsEquipmentApplyService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    @RequestMapping(params = "datagridList")
    public void datagridList(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();

        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i]);
                    }
                }
            }
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))) {
            param.put("createDate_begin", oConvertUtils.getString(param.get("createDate_begin")) + " 00:00:01");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))) {
            param.put("createDate_end", oConvertUtils.getString(param.get("createDate_end")) + " 23:59:59");
        }
		/*if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("contract_Date_begin")))) {
			param.put("contract_Date_begin", oConvertUtils.getString(param.get("contract_Date_begin")) + " 00:00:01");
		}
		if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
			param.put("contract_Date_end", oConvertUtils.getString(param.get("contract_Date_end")) + " 23:59:59");
		}*/
        wiseCoreService.selectDataGrid("datagridList", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 备件申请单新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsEquipmentApplyEntity cbsEquipmentApply, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsEquipmentApply.getId())) {
            cbsEquipmentApply = cbsEquipmentApplyService.getEntity(CbsEquipmentApplyEntity.class, cbsEquipmentApply.getId());
            req.setAttribute("cbsEquipmentApplyPage", cbsEquipmentApply);
        }
        return new ModelAndView("com/zybk/cbsequipmentapply/cbsEquipmentApply-add");
    }


    /**
     * 添加备件申请单
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsEquipmentApplyEntity cbsEquipmentApply, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "备件申请单添加成功";
        try {
            cbsEquipmentApplyService.save(cbsEquipmentApply);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请单添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 备件申请单编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsEquipmentApplyEntity cbsEquipmentApply, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsEquipmentApply.getId())) {
            cbsEquipmentApply = cbsEquipmentApplyService.getEntity(CbsEquipmentApplyEntity.class, cbsEquipmentApply.getId());
            req.setAttribute("cbsEquipmentApplyPage", cbsEquipmentApply);
        }
        return new ModelAndView("com/zybk/cbsequipmentapply/cbsEquipmentApply-update");
    }

    /**
     * 更新备件申请单
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsEquipmentApplyEntity cbsEquipmentApply, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "备件申请单更新成功";
        CbsEquipmentApplyEntity t = cbsEquipmentApplyService.get(CbsEquipmentApplyEntity.class, cbsEquipmentApply.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(cbsEquipmentApply, t);
            cbsEquipmentApplyService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请单更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除备件申请单
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsEquipmentApplyEntity cbsEquipmentApply, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, cbsEquipmentApply.getId());
        message = "备件申请单删除成功";
        try {
            cbsEquipmentApplyService.delete(cbsEquipmentApply);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除备件申请单
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "备件申请单删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class,
                        id
                );
                cbsEquipmentApplyService.delete(cbsEquipmentApply);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsequipmentapply/cbsEquipmentApplyUpload");
    }

    /**
     * 导出备件异常excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response) {
        cbsEquipmentApplyService.exportXLS(request, response);
    }

    /**
     * 导出备件审批excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportEquipmentXls")
    public void exportEquipmentXls(HttpServletRequest request, HttpServletResponse response) {
        cbsEquipmentApplyService.exportEquipmentXls(request, response);
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsEquipmentApplyEntity cbsEquipmentApply, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "备件申请单");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsEquipmentApplyEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsEquipmentApplyEntity> listCbsEquipmentApplyEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsEquipmentApplyEntity.class, params);
                for (CbsEquipmentApplyEntity cbsEquipmentApply : listCbsEquipmentApplyEntitys) {
                    cbsEquipmentApplyService.save(cbsEquipmentApply);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    @RequestMapping(params = "goApplyDetail")
    public ModelAndView goApplyDetail(HttpServletRequest req) {
        String id = req.getParameter("id");
        req.setAttribute("id", id);
        String sign = req.getParameter("sign");
        req.setAttribute("sign", sign);
        CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
        //申请人电话
        List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT\n" +
                "\tr.rolecode,u.id\n" +
                "FROM\n" +
                "\tt_s_role r\n" +
                "LEFT JOIN t_s_role_user ru ON r.id = ru.roleid\n" +
                "LEFT JOIN t_s_user u ON ru.userid = u.id\n" +
                "WHERE\n" +
                "\tu.id IN (\n" +
                "\t\tSELECT\n" +
                "\t\t\tid\n" +
                "\t\tFROM\n" +
                "\t\t\tt_s_base_user\n" +
                "\t\tWHERE\n" +
                "\t\t\tusername = '" + cbsEquipmentApplyEntity.getCreateBy() + "'\n" +
                "\t)");
        List<String> mobilePhone = new ArrayList<String>();
        if (forJdbc.get(0).get("rolecode").equals(StaticValue.RULE_CODE_THIRDPARTY_ENGINEER) || forJdbc.get(0).get("rolecode").equals(StaticValue.RULE_CODE_AREA_ENGINEER)) {
            mobilePhone = systemService.findListbySql("select cellphone from zy_engineer where ts_base_user_id='" + forJdbc.get(0).get("id") + "'");
        } else {
            mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
        }
        //获取所属单位信息
        List<String> shortname = systemService.findListbySql("SELECT\n" +
                "\tdp.shortname\n" +
                "FROM\n" +
                "\tt_s_base_user bu\n" +
                "LEFT JOIN t_s_user_org uo ON uo.user_id = bu.ID\n" +
                "LEFT JOIN t_s_depart dp on dp.ID = uo.org_id \n" +
                "WHERE bu.id='" + forJdbc.get(0).get("id") + "'");
        if (shortname.size() != 0) {
            req.setAttribute("shortname", shortname.get(0));
        }
        List<ZyEquipmentSpareEntity> sn = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", cbsEquipmentApplyEntity.getSn());
        if (sn.size() != 0) {
            req.setAttribute("spareId", sn.get(0).getId());
        }
        List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailHql = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.id='" + id + "'");
        List<CbsFaultEquipmentEntity> cbsFaultEquipmentList = systemService.findHql("from CbsFaultEquipmentEntity where applyId='" + id + "'");
        List<String> errorList = systemService.findListbySql("select id from cbs_equipment_error_log where CBS_EQUIPMENT_APPLY_ID='" + id + "'");
        if (errorList.size() != 0) {
            req.setAttribute("code", 1);
        }
        req.setAttribute("cbsFaultEquipmentList", cbsFaultEquipmentList);
        List<TSType> tSTypeHql = systemService.findHql("from TSType where TSTypegroup.typegroupname='申请优先级'");
        CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, cbsEquipmentApplyEntity.getServiceId());
        List<TSTerritory> tSTerritoryHql = systemService.findHql("from TSTerritory where territoryLevel='1'");
        List<CbsDeliverEquipmentEntity> cbsDelinerEquipmentHql = systemService.findHql("from CbsDeliverEquipmentEntity where sn='" + cbsEquipmentApplyEntity.getSn() + "'");
        List<CbsHandleLogEntity> cbsHandleLogHql = systemService.findHql("from CbsHandleLogEntity where logType=1 and businessId='" + id + "'order by createDate desc");

        //获取发货信息
        List<CbsDelinerEntity> cbsDelinerHql = systemService.findHql("from CbsDelinerEntity where equipmentApplyId.id='" + id + "'");
        List list = new ArrayList();
        if (cbsDelinerHql.size() != 0) {
            if ("1".equals(cbsDelinerHql.get(0).getIsHb())) {
                List<CbsDelinerEntity> hql = systemService.findHql("from CbsDelinerEntity where spaceNumber like '%" + cbsDelinerHql.get(0).getSpaceNumber() + "/%' or spaceNumber like '%/" + cbsDelinerHql.get(0).getSpaceNumber() + "%'");
                List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentHql = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + hql.get(0).getId() + "'");
                list.add(cbsDeliverEquipmentHql);
            } else {
                for (int i = 0; i < cbsDelinerHql.size(); i++) {
                    List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentHql = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsDelinerHql.get(i).getId() + "'");
                    list.add(cbsDeliverEquipmentHql);
                }
            }
            req.setAttribute("list", list);
        }
        // 获取备件申请单相关联的附件
        List<ZyFileLogEntity> fileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "'");
        req.setAttribute("fileList", fileList);

        List<TSType> TSTypeList = systemService.findHql("from TSType where TSTypegroup.typegroupname='申请理由'");
        req.setAttribute("TSTypeList", TSTypeList);
        req.setAttribute("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
        req.setAttribute("cbsEquipmentApplyDetailHql", cbsEquipmentApplyDetailHql);
        req.setAttribute("tSTypeHql", tSTypeHql);
        req.setAttribute("cbsService", cbsServiceEntity);
        req.setAttribute("tSTerritoryHql", tSTerritoryHql);
        req.setAttribute("cbsDelinerEquipmentHql", cbsDelinerEquipmentHql);
        req.setAttribute("cbsHandleLogHql", cbsHandleLogHql);
        req.setAttribute("mobilePhone", mobilePhone);
        return new ModelAndView("com/zybk/cbsequipmentapply/applyDetail");
    }

    @RequestMapping(params = "goPass")
    public ModelAndView goPass(HttpServletRequest req) {
        String id = req.getParameter("id");
        String sign = req.getParameter("sign");
        req.setAttribute("id", id);
        req.setAttribute("sign", sign);
        return new ModelAndView("com/zybk/cbsequipmentapply/pass");
    }

    /**
     * 备件审批 通过
     * @param req
     * @return
     */
    @RequestMapping(params = "pass")
    @ResponseBody
    public AjaxJson pass(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String so = req.getParameter("so");
        String id = req.getParameter("id");
        String csaAttention = req.getParameter("csaAttention");
        String engineerAttention = req.getParameter("engineerAttention");
        j = cbsEquipmentApplyService.pass(so,id,csaAttention,engineerAttention);
        return j;
    }

    @RequestMapping(params = "goNotPass")
    public ModelAndView goNotPass(HttpServletRequest req) {
        String id = req.getParameter("id");
        req.setAttribute("id", id);
        return new ModelAndView("com/zybk/cbsequipmentapply/notPass");
    }

    /**
     * 备件审批不通过
     * @param req
     * @return
     */
    @RequestMapping(params = "notPass")
    @ResponseBody
    public AjaxJson notPass(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String id = req.getParameter("id");
        String reasion = req.getParameter("reasion");
        j = cbsEquipmentApplyService.notPass(id, reasion);
        return j;
    }

    /**
     * @param request
     * @return
     * @author xiul
     * 2018-1-22 上午12:00:42
     * Description 设备item - 选择设备类型，单选
     */
    @RequestMapping(params = "goChooseEquipmentType")
    public ModelAndView goChooseEquipmentType(HttpServletRequest request) {
        String uuid = request.getParameter("uuid");
        String id = request.getParameter("id");
        String aId = request.getParameter("aId");
        request.setAttribute("uuid", uuid);
        request.setAttribute("id", id);
        request.setAttribute("aId", aId);
        return new ModelAndView("com/zybk/cbsequipmentapply/cbsChooseEquipmentTypeForEsItem");
    }

    /**
     * @param request
     * @return
     * @author xiul
     * 2018-1-22 上午12:00:42
     * Description 设备item - 选择设备类型，单选
     */
    @RequestMapping(params = "chooseEquipmentType")
    public ModelAndView chooseEquipmentType(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsequipmentapply/chooseEquipmentTypeForEsItem");
    }

    /**
     * @param zyEquipmentTypeEntity
     * @param request
     * @param response
     * @author xiul
     * 2018-1-22 上午12:00:42
     * Description 设备item - 选择设备类型datagrid加载
     */
    @RequestMapping(params = "dataGridOfChooseEquipmentType")
    @ResponseBody
    public List<TreeGrid> dataGridOfChooseEquipmentType(ZyEquipmentTypeEntity zyEquipmentTypeEntity, HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
        CriteriaQuery cq;
        List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
        cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
        cq.notEq("typeDesc", "设备");
        if (treegrid.getId() != null) {
            cq.eq("equipmentType.id", treegrid.getId());
        } else if (treegrid.getId() == null) {
            cq.isNull("equipmentType.id");
            //cq.eq("equipmentType.id","402883f3545bca4101545bdde56f0004");
        }
        cq.add();
        List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setIdField("id");
        treeGridModel.setTextField("typeDesc");
        treeGridModel.setParentId("equipmentType_id");
        treeGridModel.setParentText("equipmentType_typeDesc");
        treeGridModel.setSrc("");
        treeGridModel.setChildList("childEquipmentTypes");
        treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
        return treeGrids;
    }

    @RequestMapping(params = "getItem")
    @ResponseBody
    public List<ZyEsItemEntity> getItem(HttpServletRequest request) {
        String id = request.getParameter("id");
        String applyDetailId = request.getParameter("applyId");
        String aId = request.getParameter("aId");
        CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, aId);
        ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, id);
        if ("未知备件".equals(zyEquipmentType.getTypeDesc())) {
            return null;
        }
        List<ZyEsItemEntity> hql = systemService.findHql("from ZyEsItemEntity where type.id='" + id + "' and scope like'%" + cbsEquipmentApply.getEquipmentType() + "%' order by item");
        return hql;
    }

    @RequestMapping(params = "getItemDesc")
    @ResponseBody
    public ZyEsItemEntity getItemDesc(HttpServletRequest request) {
        String id = request.getParameter("id");
        ZyEsItemEntity entity = systemService.getEntity(ZyEsItemEntity.class, id);
        return entity;
    }

    @RequestMapping(params = "delSpare")
    @ResponseBody
    public AjaxJson delSpare(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String applyDetailId = request.getParameter("applyDetailId");
        systemService.deleteEntityById(CbsEquipmentApplyDetailEntity.class, applyDetailId);
        j.setSuccess(true);
        return j;
    }

    @RequestMapping(params = "updateSparepartApply")
    @ResponseBody
    public AjaxJson updateSparepartApply(HttpServletRequest request, CbsEquipmentApplyDetailEntity applyDetailEntity) {

        AjaxJson j = new AjaxJson();
        //故障备件信息
        String[] type_ids = request.getParameterValues("type_ids");
        String[] type_dess = request.getParameterValues("type_dess");
        String[] item_ids = request.getParameterValues("item_ids");
        String[] itemms = request.getParameterValues("itemms");
        String[] s_ns = request.getParameterValues("s_ns");
        String[] equipment_ercodes = request.getParameterValues("equipment_ercodes");
        //修改备件
        String[] applyDetailIds = request.getParameterValues("applyDetailIds");
        String[] typeIds = request.getParameterValues("typeIds");
        String[] typeDess = request.getParameterValues("typeDess");
        String[] itemIds = request.getParameterValues("itemIds");
        String[] items = request.getParameterValues("items");
        String[] totals = request.getParameterValues("totals");
        String[] applyLayers = request.getParameterValues("applyLayers");
        String[] memos = request.getParameterValues("memos");
        String[] fileIds = request.getParameterValues("fileIds");
        String sr = request.getParameter("sr");
        String radiobutton = request.getParameter("radiobutton");
        String warehouse = request.getParameter("warehouse");
        String applyId = request.getParameter("aid");
        String userName = request.getParameter("userName");
        String phone = request.getParameter("phone");
        String memo = request.getParameter("memo");
        String sheng = request.getParameter("sheng");
        String shi = request.getParameter("shi");
        String cinemaName = request.getParameter("cinemaName");
        String applyReason = request.getParameter("applyReason");
        String address = request.getParameter("address");
        String sign = request.getParameter("sign");
        String sn = request.getParameter("sn");
        CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, applyId);
        TSUser user = ResourceUtil.getSessionUserName();
        //创建一个新的备件申请单并将原备件置办为未通过
        if ("1".equals(sign) && cbsEquipmentApply.getJudge() == 1) {
            systemService.updateBySqlString("update CBS_EQUIPMENT_APPLY set memo='工程师修改备件申请',status='3',update_date = NOW(),update_by='" + user.getUserName() + "',update_name='" + user.getRealName() + "' where id='" + applyId + "'");

            CbsEquipmentApplyEntity cbsEquipmentApplyEntity = new CbsEquipmentApplyEntity();
            CbsServiceEntity cbsServiceEntity = cbsServiceService.getEntity(CbsServiceEntity.class, cbsEquipmentApply.getServiceId());
            String fId = "";
            if (fileIds != null) {
                for (int i = 0; i < fileIds.length; i++) {
                    fId += "," + fileIds[i];
                }
                cbsEquipmentApplyEntity.setFileId(fId.substring(1));
            }
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyyMMdd");
            String time = format.format(date);
            StringBuffer buffer = new StringBuffer();
            buffer.append("CO");
            buffer.append(time);
            List<Object[]> cbsEquipmentApplyList = systemService.findListbySql("select * from cbs_equipment_apply where to_days(create_date) = to_days(now()) ORDER BY record_id desc;");
            if ("否".equals(radiobutton)) {
                if (cbsEquipmentApplyList.size() == 0) {
                    buffer.append("001");
                    String s = buffer.toString();
                    cbsEquipmentApplyEntity.setRecordId(s);
                    List<TSTerritory> shengList = systemService.findByProperty(TSTerritory.class, "territoryCode", sheng);
                    cbsEquipmentApplyEntity.setSheng(shengList.get(0));
                    List<TSTerritory> shiList = systemService.findByProperty(TSTerritory.class, "territoryCode", shi);
                    cbsEquipmentApplyEntity.setShi(shiList.get(0));
                    cbsEquipmentApplyEntity.setZt(2);
                    cbsEquipmentApplyEntity.setStatus(1);
                    cbsEquipmentApplyEntity.setSn(sn);
                    cbsEquipmentApplyEntity.setServiceId(cbsServiceEntity.getId());
                    cbsEquipmentApplyEntity.setEquipmentType(cbsEquipmentApply.getEquipmentType());
                    cbsEquipmentApplyEntity.setPhone(phone);
                    cbsEquipmentApplyEntity.setUserName(userName);
                    cbsEquipmentApplyEntity.setCinemaName(cinemaName);
                    cbsEquipmentApplyEntity.setApplyReason(applyReason);
                    cbsEquipmentApplyEntity.setAddress(address);
                    cbsEquipmentApplyEntity.setMemo(memo);
                    List<Integer> listbySql = systemService.findListbySql("select judge from CBS_EQUIPMENT_APPLY where id='" + applyId + "'");
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 2) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(2);
                    }
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 1) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(1);
                    }
                    if (cbsServiceEntity.getSr() != null) {
                        cbsEquipmentApplyEntity.setSrCode(cbsServiceEntity.getSr());
                    }
                    systemService.saveOrUpdate(cbsEquipmentApplyEntity);
                } else {
                    String o = (String) cbsEquipmentApplyList.get(0)[1];
                    String s = o.substring(10, 13);
                    int i = Integer.parseInt(s);
                    i++;
                    if (i <= 9) {
                        buffer.append("00" + i);
                    } else if (i >= 10 && i < 100) {
                        buffer.append("0" + i);
                    } else {
                        buffer.append(i);
                    }
                    String string = buffer.toString();
                    cbsEquipmentApplyEntity.setRecordId(string);
                    List<TSTerritory> shengList = systemService.findByProperty(TSTerritory.class, "territoryCode", sheng);
                    cbsEquipmentApplyEntity.setSheng(shengList.get(0));
                    List<TSTerritory> shiList = systemService.findByProperty(TSTerritory.class, "territoryCode", shi);
                    cbsEquipmentApplyEntity.setShi(shiList.get(0));
                    cbsEquipmentApplyEntity.setZt(2);
                    cbsEquipmentApplyEntity.setStatus(1);
                    cbsEquipmentApplyEntity.setSn(sn);
                    cbsEquipmentApplyEntity.setServiceId(cbsServiceEntity.getId());
                    cbsEquipmentApplyEntity.setEquipmentType(cbsEquipmentApply.getEquipmentType());
                    cbsEquipmentApplyEntity.setPhone(phone);
                    cbsEquipmentApplyEntity.setUserName(userName);
                    cbsEquipmentApplyEntity.setCinemaName(cinemaName);
                    cbsEquipmentApplyEntity.setApplyReason(applyReason);
                    cbsEquipmentApplyEntity.setAddress(address);
                    cbsEquipmentApplyEntity.setMemo(memo);
                    List<Integer> listbySql = systemService.findListbySql("select judge from CBS_EQUIPMENT_APPLY where id='" + applyId + "'");
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 2) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(2);
                    }
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 1) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(1);
                    }
                    if (cbsServiceEntity.getSr() != null) {
                        cbsEquipmentApplyEntity.setSrCode(cbsServiceEntity.getSr());
                    }
                    systemService.saveOrUpdate(cbsEquipmentApplyEntity);
                }
            } else {
                if (cbsEquipmentApplyList.size() == 0) {
                    buffer.append("001");
                    String s = buffer.toString();
                    cbsEquipmentApplyEntity.setRecordId(s);
                    List<CbsWarehouseEntity> warehouseList = systemService.findByProperty(CbsWarehouseEntity.class, "id", warehouse);
                    if (warehouseList.size() != 0) {
                        TSTerritory shengList = warehouseList.get(0).getSheng();
                        cbsEquipmentApplyEntity.setSheng(shengList);
                        TSTerritory shiList = warehouseList.get(0).getShi();
                        cbsEquipmentApplyEntity.setShi(shiList);
                        cbsEquipmentApplyEntity.setAddress(warehouseList.get(0).getAddress());
                        cbsEquipmentApplyEntity.setWarehouseId(warehouse);
                    }
                    cbsEquipmentApplyEntity.setZt(1);
                    cbsEquipmentApplyEntity.setStatus(1);
                    cbsEquipmentApplyEntity.setSn(sn);
                    cbsEquipmentApplyEntity.setServiceId(cbsServiceEntity.getId());
                    cbsEquipmentApplyEntity.setEquipmentType(cbsEquipmentApply.getEquipmentType());
                    cbsEquipmentApplyEntity.setPhone(phone);
                    cbsEquipmentApplyEntity.setUserName(userName);
                    cbsEquipmentApplyEntity.setCinemaName(cinemaName);
                    cbsEquipmentApplyEntity.setApplyReason(applyReason);
                    cbsEquipmentApplyEntity.setAddress(address);
                    cbsEquipmentApplyEntity.setMemo(memo);
                    List<Integer> listbySql = systemService.findListbySql("select judge from CBS_EQUIPMENT_APPLY where id='" + applyId + "'");
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 2) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(2);
                    }
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 1) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(1);
                    }
                    if (cbsServiceEntity.getSr() != null) {
                        cbsEquipmentApplyEntity.setSrCode(cbsServiceEntity.getSr());
                    }
                    systemService.saveOrUpdate(cbsEquipmentApplyEntity);
                } else {
                    String o = (String) cbsEquipmentApplyList.get(0)[1];
                    String s = o.substring(10, 13);
                    int i = Integer.parseInt(s);
                    i++;
                    if (i <= 9) {
                        buffer.append("00" + i);
                    } else if (i >= 10 && i < 100) {
                        buffer.append("0" + i);
                    } else {
                        buffer.append(i);
                    }
                    String string = buffer.toString();
                    cbsEquipmentApplyEntity.setRecordId(string);
                    List<CbsWarehouseEntity> warehouseList = systemService.findByProperty(CbsWarehouseEntity.class, "id", warehouse);
                    if (warehouseList.size() != 0) {
                        TSTerritory shengList = warehouseList.get(0).getSheng();
                        cbsEquipmentApplyEntity.setSheng(shengList);
                        TSTerritory shiList = warehouseList.get(0).getShi();
                        cbsEquipmentApplyEntity.setShi(shiList);
                        cbsEquipmentApplyEntity.setAddress(warehouseList.get(0).getAddress());
                        cbsEquipmentApplyEntity.setWarehouseId(warehouse);
                    }
                    cbsEquipmentApplyEntity.setZt(1);
                    cbsEquipmentApplyEntity.setStatus(1);
                    cbsEquipmentApplyEntity.setSn(sn);
                    cbsEquipmentApplyEntity.setServiceId(cbsServiceEntity.getId());
                    cbsEquipmentApplyEntity.setEquipmentType(cbsEquipmentApply.getEquipmentType());
                    cbsEquipmentApplyEntity.setPhone(phone);
                    cbsEquipmentApplyEntity.setUserName(userName);
                    cbsEquipmentApplyEntity.setCinemaName(cinemaName);
                    cbsEquipmentApplyEntity.setApplyReason(applyReason);
                    cbsEquipmentApplyEntity.setAddress(address);
                    cbsEquipmentApplyEntity.setMemo(memo);
                    List<Integer> listbySql = systemService.findListbySql("select judge from CBS_EQUIPMENT_APPLY where id='" + applyId + "'");
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 2) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(2);
                    }
                    if (StringUtil.isNotEmpty(listbySql.get(0)) && listbySql.get(0) == 1) {
                        cbsEquipmentApplyEntity.setCreateBy(cbsEquipmentApply.getCreateBy());
                        cbsEquipmentApplyEntity.setCinemaName(cbsEquipmentApply.getCreateName());
                        cbsEquipmentApplyEntity.setJudge(1);
                    }
                    if (cbsServiceEntity.getSr() != null) {
                        cbsEquipmentApplyEntity.setSrCode(cbsServiceEntity.getSr());
                    }
                    systemService.saveOrUpdate(cbsEquipmentApplyEntity);
                }
            }
            List<CbsEquipmentApplyEntity> cbsEquipmentApplyhql = systemService.findHql("from CbsEquipmentApplyEntity  order by createDate desc");
            /*两小时未审批自动通过*/
            //cbsServiceService.updateSpareStatus(cbsEquipmentApplyhql.get(0).getId(), user.getRealName());
            //加入日志
            CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
            cbsServiceLog.setCbsServiceId(cbsServiceEntity);
            cbsServiceLog.setDescription("备件申请单中的附件");
            List<ZyFileLogEntity> zyFileLoghql = systemService.findHql("from ZyFileLogEntity  where business_type='F' AND createName='" + user.getRealName() + "' order by createDate desc");
            if (zyFileLoghql.size() != 0) {
                cbsServiceLog.setZyFileLogId(zyFileLoghql.get(0));
            }
            systemService.save(cbsServiceLog);
            CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
            cbsHandleLog.setBusinessId(cbsEquipmentApplyhql.get(0).getId());
            cbsHandleLog.setLogType(1);
            cbsHandleLog.setDescription("创建了备件申请");
            systemService.save(cbsHandleLog);

            //备件申请详细
            if (typeIds != null) {
                for (int i = 0; i < typeIds.length; i++) {
                    CbsEquipmentApplyDetailEntity applyDetail = new CbsEquipmentApplyDetailEntity();
                    ZyEquipmentTypeEntity zyEquipmentTypeEntity = systemService.getEntity(ZyEquipmentTypeEntity.class, typeIds[i]);
                    applyDetail.setTypeId(zyEquipmentTypeEntity);
                    applyDetail.setTypeDes(typeDess[i]);
                    if (!"未知备件".equals(zyEquipmentTypeEntity.getTypeDesc())) {
                        ZyEsItemEntity entity = systemService.getEntity(ZyEsItemEntity.class, itemIds[i]);
                        applyDetail.setItemId(entity);
                        if (entity != null) {
                            applyDetailEntity.setItemDesc(entity.getItemDesc());
                            applyDetail.setItem(entity.getItem());
                        }
                    } else {
                        applyDetail.setItem(items[i].trim());
                        //通过备件号反查ID和Type并保存
                        List<ZyEsItemEntity> itemf = systemService.findHql("from ZyEsItemEntity where item='"+items[i].trim()+"'");
                        if(itemf.size() > 0){
                        	applyDetail.setItemId(itemf.get(0));
                        	applyDetail.setItemDesc(itemf.get(0).getItemDesc());
                        	applyDetail.setItem(itemf.get(0).getItem());
                            ZyEquipmentTypeEntity Typef = itemf.get(0).getType();
                            if (Typef != null) {
                            	applyDetail.setTypeId(Typef);
                            	applyDetail.setTypeDes(Typef.getTypeDesc());
                            }
                        }
                    }
                    List<CbsEquipmentApplyEntity> hql = systemService.findHql("from CbsEquipmentApplyEntity order by createDate desc");
                    applyDetail.setApplyId(hql.get(0));
                    if ("".equals(totals[i])) {
                        totals[i] = String.valueOf(0);
                    }
                    applyDetail.setTotal(Integer.valueOf(totals[i]));
                    applyDetail.setApplyLayer(Integer.valueOf(applyLayers[i]));
                    applyDetail.setMemo(memos[i]);
                    applyDetail.setSn(hql.get(0).getSn());
                    systemService.saveOrUpdate(applyDetail);
                }
            }
            //备件申请单ID
            List<String> listbySql1 = systemService.findListbySql("select id  from cbs_equipment_apply where create_name='" + user.getRealName() + "' ORDER BY create_date desc LIMIT 0,1");
            if (fileIds != null) {
                for (int i = 0; i < fileIds.length; i++) {
                    systemService.updateBySqlString("update zy_file_log set business_key = '" + listbySql1.get(0) + "' where id = '" + fileIds[i] + "'");
                }
            }
            if (type_ids != null) {
                for (int i = 0; i < type_ids.length; i++) {
                    CbsFaultEquipmentEntity cbsFaultEquipmentEntity = new CbsFaultEquipmentEntity();
                    cbsFaultEquipmentEntity.setTypeId(type_ids[i]);
                    cbsFaultEquipmentEntity.setTypeDes(type_dess[i]);
                    ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, type_ids[i]);
                    if (!"未知备件".equals(zyEquipmentType.getTypeDesc())) {
                        ZyEsItemEntity entity = systemService.getEntity(ZyEsItemEntity.class, item_ids[i]);
                        if (entity != null) {
                            cbsFaultEquipmentEntity.setItemId(item_ids[i]);
                            cbsFaultEquipmentEntity.setItem(entity.getItem() != null ? entity.getItem() : "");
                        }
                    } else {
                        cbsFaultEquipmentEntity.setItem(itemms[i]);
                        //通过备件号反查ID和Type并保存
                        List<ZyEsItemEntity> itemf = systemService.findHql("from ZyEsItemEntity where item='"+itemms[i].trim()+"'");
                        if(itemf.size() > 0){
                        	cbsFaultEquipmentEntity.setItemId(itemf.get(0).getId());
                        	cbsFaultEquipmentEntity.setItem(itemf.get(0).getItem());
                            ZyEquipmentTypeEntity Typef = itemf.get(0).getType();
                            if (Typef != null) {
                            	cbsFaultEquipmentEntity.setTypeId(Typef.getId());
                            	cbsFaultEquipmentEntity.setTypeDes(Typef.getTypeDesc());
                            }
                        }
                    }
                    List<CbsEquipmentApplyEntity> hql = systemService.findHql("from CbsEquipmentApplyEntity order by createDate desc");
                    cbsFaultEquipmentEntity.setApplyId(hql.get(0).getId());
                    cbsFaultEquipmentEntity.setCode(hql.get(0).getRecordId());
                    cbsFaultEquipmentEntity.setSn(s_ns[i]);
                    cbsFaultEquipmentEntity.setEquipmentErcode(equipment_ercodes[i]);
                    systemService.saveOrUpdate(cbsFaultEquipmentEntity);
                }
            }

            //备件序列号验证
            cbsServiceService.snValiDate(cbsEquipmentApply.getServiceId(), s_ns);
        } else {
            cbsEquipmentApply.setUserName(userName);
            cbsEquipmentApply.setPhone(phone);
            cbsEquipmentApply.setMemo(memo);
            cbsEquipmentApply.setCinemaName(cinemaName);
            cbsEquipmentApply.setApplyReason(applyReason);
            StringBuffer fileBuffer = new StringBuffer();
            List<String> strings = new ArrayList<>();
            if (cbsEquipmentApply.getFileId() != null & !"".equals(cbsEquipmentApply.getFileId())) {
                fileBuffer.append(cbsEquipmentApply.getFileId());
                String[] split = cbsEquipmentApply.getFileId().split(",");
                for (int i = 0; i < split.length; i++) {
                    strings.add(split[i]);
                }
            }
            if (fileIds != null) {
                for (int i = 0; i < fileIds.length; i++) {
                    if (strings.size() != 0 && strings.contains(fileIds[i])) {
                        continue;
                    }
                    fileBuffer.append("," + fileIds[i]);
                }
            }
            if (cbsEquipmentApply.getFileId() != null & !"".equals(cbsEquipmentApply.getFileId())) {
                cbsEquipmentApply.setFileId(fileBuffer.toString());
            } else {
                if (fileBuffer.toString().length() != 0) {
                    cbsEquipmentApply.setFileId(fileBuffer.toString().substring(1));
                }
            }

            if ("否".equals(radiobutton)) {
                List<TSTerritory> shengList = systemService.findByProperty(TSTerritory.class, "territoryCode", sheng);
                cbsEquipmentApply.setSheng(shengList.get(0));
                List<TSTerritory> shiList = systemService.findByProperty(TSTerritory.class, "territoryCode", shi);
                cbsEquipmentApply.setShi(shiList.get(0));
                cbsEquipmentApply.setZt(2);
                cbsEquipmentApply.setWarehouseId(null);
                cbsEquipmentApply.setAddress(address);
                cbsEquipmentApply.setSrCode(sr);
                systemService.saveOrUpdate(cbsEquipmentApply);
            } else {
                List<CbsWarehouseEntity> warehouseList = systemService.findByProperty(CbsWarehouseEntity.class, "id", warehouse);
                if (warehouseList.size() != 0) {
                    TSTerritory shengList = warehouseList.get(0).getSheng();
                    cbsEquipmentApply.setSheng(shengList);
                    TSTerritory shiList = warehouseList.get(0).getShi();
                    cbsEquipmentApply.setShi(shiList);
                    cbsEquipmentApply.setAddress(warehouseList.get(0).getAddress());
                    cbsEquipmentApply.setWarehouseId(warehouse);
                }
                cbsEquipmentApply.setZt(1);
                cbsEquipmentApply.setSrCode(sr);
                systemService.saveOrUpdate(cbsEquipmentApply);
            }
            //故障备件
            if (type_ids != null) {
                for (int i = 0; i < type_ids.length; i++) {
                    CbsFaultEquipmentEntity cbsFaultEquipmentEntity = new CbsFaultEquipmentEntity();
                    cbsFaultEquipmentEntity.setTypeId(type_ids[i]);
                    cbsFaultEquipmentEntity.setTypeDes(type_dess[i]);
                    ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, type_ids[i]);
                    if (!"未知备件".equals(zyEquipmentType.getTypeDesc())) {
                        ZyEsItemEntity entity = systemService.getEntity(ZyEsItemEntity.class, item_ids[i]);
                        if (entity != null) {
                            cbsFaultEquipmentEntity.setItemId(item_ids[i]);
                            cbsFaultEquipmentEntity.setItem(entity.getItem() != null ? entity.getItem() : "");
                        }
                    } else {
                        cbsFaultEquipmentEntity.setItem(itemms[i]);
                        //通过备件号反查ID和Type并保存
                        List<ZyEsItemEntity> itemf = systemService.findHql("from ZyEsItemEntity where item='"+itemms[i].trim()+"'");
                        if(itemf.size() > 0){
                        	cbsFaultEquipmentEntity.setItemId(itemf.get(0).getId());
                        	cbsFaultEquipmentEntity.setItem(itemf.get(0).getItem());
                            ZyEquipmentTypeEntity Typef = itemf.get(0).getType();
                            if (Typef != null) {
                            	cbsFaultEquipmentEntity.setTypeId(Typef.getId());
                            	cbsFaultEquipmentEntity.setTypeDes(Typef.getTypeDesc());
                            }
                        }
                    }
                    List<CbsEquipmentApplyEntity> hql = systemService.findHql("from CbsEquipmentApplyEntity where id='" + applyId + "'");
                    cbsFaultEquipmentEntity.setApplyId(hql.get(0).getId());
                    cbsFaultEquipmentEntity.setCode(hql.get(0).getRecordId());
                    cbsFaultEquipmentEntity.setSn(s_ns[i]);
                    cbsFaultEquipmentEntity.setEquipmentErcode(equipment_ercodes[i]);
                    systemService.saveOrUpdate(cbsFaultEquipmentEntity);
                }
            }
            //加入日志
            CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
            cbsHandleLog.setBusinessId(applyDetailEntity.getId());
            cbsHandleLog.setDescription("修改了备件申请");
            cbsHandleLog.setLogType(1);
            systemService.save(cbsHandleLog);
            if (typeIds != null) {
                for (int i = 0; i < typeIds.length; i++) {
                    if (applyDetailIds != null && i < applyDetailIds.length) {
                        applyDetailEntity = systemService.getEntity(CbsEquipmentApplyDetailEntity.class, applyDetailIds[i]);
                    } else {
                        applyDetailEntity = new CbsEquipmentApplyDetailEntity();
                    }
                    ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, typeIds[i]);
                    applyDetailEntity.setTypeId(zyEquipmentType);
                    applyDetailEntity.setTypeDes(typeDess[i]);
                    if (!"未知备件".equals(zyEquipmentType.getTypeDesc())) {
                        ZyEsItemEntity entity = systemService.getEntity(ZyEsItemEntity.class, itemIds[i]);
                        applyDetailEntity.setItemId(entity);
                        if (entity != null) {
                            applyDetailEntity.setItemDesc(entity.getItemDesc());
                            applyDetailEntity.setItem(entity.getItem());
                        }
                    } else {
                        applyDetailEntity.setItem(items[i].trim());
                        //通过备件号反查ID和Type并保存
                        List<ZyEsItemEntity> itemf = systemService.findHql("from ZyEsItemEntity where item='"+items[i].trim()+"'");
                        if(itemf.size() > 0){
                      	  applyDetailEntity.setItemId(itemf.get(0));
                            applyDetailEntity.setItemDesc(itemf.get(0).getItemDesc());
                            applyDetailEntity.setItem(itemf.get(0).getItem());
                            ZyEquipmentTypeEntity Typef = itemf.get(0).getType();
                            if (Typef != null) {
                                applyDetailEntity.setTypeId(Typef);
                                applyDetailEntity.setTypeDes(Typef.getTypeDesc());
                            }
                        }
                    }
                    CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, applyId);
                    applyDetailEntity.setApplyId(cbsEquipmentApplyEntity);
                    applyDetailEntity.setTotal(Integer.valueOf(totals[i]));
                    applyDetailEntity.setApplyLayer(Integer.valueOf(applyLayers[i]));
                    applyDetailEntity.setMemo(memos[i]);
                    applyDetailEntity.setSn(sn);
                    systemService.saveOrUpdate(applyDetailEntity);
                }
            }
            if (fileIds != null) {
                for (int i = 0; i < fileIds.length; i++) {
                    systemService.updateBySqlString("update zy_file_log set business_key = '" + applyId + "' where id = '" + fileIds[i] + "'");
                }
            }
            
          //备件序列号验证
            cbsServiceService.snValiDate(cbsEquipmentApply.getServiceId(), s_ns);
        }
        j.setSuccess(true);
        j.setMsg(sign);
        return j;
    }

    /**
     * 删除上传的文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "delFile")
    public AjaxJson delFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String id = oConvertUtils.getString(request.getParameter("id"));
            String applyId = request.getParameter("applyId");
            if (id != null && id != "") {
                systemService.deleteEntityById(ZyFileLogEntity.class, id);
                int i = systemService.updateBySqlString("DELETE FROM cbs_service_log WHERE zy_file_log_id = '" + id + "'");
                if (applyId != null && applyId != "") {
                    CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, applyId);
                    String fileId = cbsEquipmentApplyEntity.getFileId();
                    String[] fileSplit = fileId.split(",");
                    List fileList = new ArrayList();
                    for (int k = 0; k < fileSplit.length; k++) {
                        fileList.add(fileSplit[k]);
                    }
                    if (fileList.contains(id)) {
                        fileList.remove(id);
                    }
                    String fId = "";
                    for (int l = 0; l < fileList.size(); l++) {
                        fId += "," + fileList.get(l);
                    }
                    if ("".equals(fId)) {
                        systemService.updateBySqlString("update CBS_EQUIPMENT_APPLY set FILE_ID='' where id='" + applyId + "'");
                    } else {
                        systemService.updateBySqlString("update CBS_EQUIPMENT_APPLY set FILE_ID='" + fId.substring(1) + "' where id='" + applyId + "'");
                    }
                }
                j.setMsg("文件删除成功");
                j.setSuccess(true);
            }
        } catch (Exception e) {
            j.setMsg(e.getMessage());
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    @RequestMapping(params = "delFaultEquipment")
    @ResponseBody
    public AjaxJson delFaultEquipment(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String id = request.getParameter("id");
        systemService.deleteEntityById(CbsFaultEquipmentEntity.class, id);
        j.setSuccess(true);
        j.setMsg("操作成功");
        return j;
    }
    /*备件申请审批通过后两个小时（该时限可以人为设置）后，发货单状态仍是“CSA待发货”，则向CSA发送短信和邮件通知。*/
    public void selectStatus(final String id) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                List<CbsDelinerEntity> cbsDelinerHql = systemService.findHql("from CbsDelinerEntity where status=1 and equipmentApplyId.id = '" + id + "' order by createDate desc");
                if (cbsDelinerHql.size() != 0) {
                    CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
                    //获取服务商信息
                    List<String> shortnames = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApply.getServiceId() + "'");
                    List<CbsServiceEntity> cbsServiceList = systemService.findHql("from CbsServiceEntity where id='" + cbsEquipmentApply.getServiceId() + "'");
                    List<ZyEngineerEntity> zyEngineerHql = systemService.findHql("from ZyEngineerEntity where id = '" + cbsServiceList.get(0).getEngineer() + "'");
                    List<TSUser> hql = systemService.findHql("from TSUser where id='" + cbsEquipmentApply.getApproveUser() + "'");
                    List<String> mobilePhoneList = systemService.findListbySql("select mobilePhone from t_s_user u LEFT JOIN t_s_base_user bu on u.id = bu.id where bu.username = '" + cbsEquipmentApply.getCreateBy() + "'");
                    if (StaticValue.CSAdfh.equals(cbsDelinerHql.get(0).getStatus())) {
                        String shortname = "";
                        String zyEnginee = "";
                        if (zyEngineerHql.size() != 0 && zyEngineerHql.get(0).getName() != null) {
                            zyEnginee = zyEngineerHql.get(0).getName();
                        }
                        if (shortnames.size() != 0) {
                            shortname = shortnames.get(0);
                        }
                        String emailTital = "备件发货超时提醒：<" + cbsDelinerHql.get(0).getCode() + ">-<" + cbsServiceList.get(0).getLevel() + ">-<" + cbsServiceList.get(0).getCode() + ">-<" + cbsServiceList.get(0).getZyCinemaName() + ">-" + getDateStr(new Date());
                        String emailContent = "Dear CSA同事们，发货单:<" + cbsDelinerHql.get(0).getCode() + ">尚未发货，请及时处理。\n" +
                                "发货单号：<" + cbsDelinerHql.get(0).getCode() + ">。\n" +
                                "备件申请人：<" + shortname + "> <" + cbsEquipmentApply.getCreateName() + "> <" + mobilePhoneList.get(0) + ">。\n" +
                                "备件审批人： <" + hql.get(0).getRealName() + "> <" + hql.get(0).getMobilePhone() + ">。\n" +
                                "具体内容请查看http://cbs.cfg-barco.com\n" +
                                "【中影巴可客服部】\n" +
                                "* 该邮件请勿回复";
                        List<String> listbySql = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
                        for (int i = 0; i < listbySql.size(); i++) {
                            SendMailUtil.sendeMail(listbySql.get(i), emailTital, emailContent, systemService);
                        }
                    }
                    List<String> listbySql1 = systemService.findListbySql("select mobilePhone from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
                	// add start 190125 Amy 9点30之前和21点之后不提醒
                	Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    int hour = calendar.get(Calendar.HOUR_OF_DAY);
                    int minutes = calendar.get(Calendar.MINUTE);
                	if (hour < 9 || hour >= 21 || (hour == 9 && minutes < 30)) {
                	} else {
	                    for (int i = 0; i < listbySql1.size(); i++) {
	                        SendMessage.sendSMSWithContent(listbySql1.get(i), "发货单号<" + cbsDelinerHql.get(0).getCode() + ">尚未发货，请及时处理。详情请查看CBS系统", systemService);
	                    }
                	}
                    // add end 190125 Amy 9点30之前和21点之后不提醒
                }
            }
        }, StaticValue.selectStatusTiem);
    }

    /*获取Sr号*/
    public void getSr(final String id) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, id);
                    List<String> sr = SimpleMailReceiver.getSr();
                    String s = "";
                    for (int i = 0; i < sr.size(); i++) {
                        String[] split = sr.get(i).split("-");
                        if (sr.get(i).contains("Barco Service Request") && sr.get(i).contains(cbsService.getCode())) {
                            s = sr.get(i).substring(22, 30);
                            break;
                        }
                    }
                    System.out.println("邮件解析出来的sr="+s);
                    logger.debug("邮件解析出来的sr="+s);
                    cbsService.setSr(s);
                    systemService.saveOrUpdate(cbsService);
                    systemService.updateBySqlString("update cbs_equipment_apply set sr_code='" + s + "' where service_id='" + cbsService.getId() + "'");
                    systemService.updateBySqlString("update cbs_deliver set sr_code='" + s + "' where cr_code='" + cbsService.getCode() + "'");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 60000);
    }

    //如果该备件申请关联的服务单没有SR号，则向SFDC发送创单邮件
    public void sendEmailToSFDC(CbsEquipmentApplyEntity cbsEquipmentApply) {
//        CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, cbsEquipmentApply.getServiceId());
//        if (StringUtil.isEmpty(cbsService.getSr())) {
//            List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailHql = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId='" + cbsEquipmentApply.getId() + "'");
//            StringBuffer itemBuffer = new StringBuffer();
//            StringBuffer totalBuffer = new StringBuffer();
//            for (int i = 0; i < cbsEquipmentApplyDetailHql.size(); i++) {
//                itemBuffer.append("," + cbsEquipmentApplyDetailHql.get(i).getItem());
//                totalBuffer.append("," + cbsEquipmentApplyDetailHql.get(i).getTotal());
//            }
//            String s = itemBuffer.toString().substring(1, itemBuffer.toString().length());
//            String s1 = "";
//            if (totalBuffer.toString().length() > 2) {
//                s1 = totalBuffer.toString().substring(1, totalBuffer.toString().length());
//            } else {
//                String[] split = totalBuffer.toString().split(",");
//                s1 = split[1];
//            }
//            List<String> snList = systemService.findListbySql("select type_desc from zy_equipment_type where id=(select type from zy_equipment_spare where sn='" + cbsService.getSn() + "')");
//            String serviceType1 = "";
//            String serviceType2 = "";
//            String errorType1 = "";
//            String errorType2 = "";
//            String sn = "";
//            if (snList.size() != 0 && StringUtil.isNotEmpty(snList.get(0))) {
//                sn = snList.get(0);
//            }
//            if (cbsService.getServiceType1() != null && cbsService.getServiceType2() != null) {
//                serviceType1 = cbsService.getServiceType1().getName();
//                serviceType2 = cbsService.getServiceType2().getName();
//            }
//            if (cbsService.getErrorType1() != null && cbsService.getErrorType2() != null) {
//                errorType1 = cbsService.getErrorType1().getName();
//                errorType2 = cbsService.getErrorType2().getName();
//            }
//            String bp = "";
//            List<String> bpList = systemService.findListbySql("select bp_no from zy_equipment_spare where sn='" + cbsService.getSn().trim() + "'");
//            if (bpList.size() != 0 && StringUtil.isNotEmpty(bpList.get(0))) {
//                bp = bpList.get(0);
//            }
//            String emailTital = "NewSR <" + serviceType1 + "," + serviceType2 + ">-<" + cbsService.getCode() + ">-<" + cbsService.getZyCinemaName() + ">";
//            String emailContent = " 影院名称：" + cbsService.getZyCinemaName() + "\n" +
//                    "服务单号：" + cbsService.getCode() + "\n" +
//                    "设备序列号：" + cbsService.getSn() + "\n" +
//                    "BP：" + bp + "\n" +
//                    "联系人：" + cbsService.getContactsName() +" - " + cbsService.getContactsPhone()+"\n" +
//                    "产品分类：" + sn + "\n" +
//                    "故障分类1：" + errorType1 + "\n" +
//                    "故障分类2：" + errorType2 + "\n" +
//                    "级别：" + cbsService.getLevel() + "\n" +
//                    "故障描述：" + cbsService.getDescription() + "\n" +
//                    "报修时间：" + cbsService.getCreateDate() + "\n" +
//                    "备件申请：备件号:" + s + " 数量: " + s1 + "";
//            SendMailUtil.sendeMail("service.DC.china@barco.com", emailTital, emailContent, systemService);
//            getSr(cbsService.getId());
//        }
    }

    @RequestMapping(params = "getDetial")
    public ModelAndView getDetial(HttpServletRequest req) {
        List<CbsHandleLogEntity> cbsHandleLogHql = systemService.findHql("from CbsHandleLogEntity where logType=1 order by createDate desc");
        req.setAttribute("cbsHandleLogHql", cbsHandleLogHql);
        return new ModelAndView("com/zybk/cbsequipmentapply/getDetial");
    }

    @RequestMapping(params = "goSpareApplyDetail")
    public ModelAndView goSpareApplyDetail(HttpServletRequest req) {
        String id = req.getParameter("applyId");
        req.setAttribute("id", id);
        String sign = req.getParameter("sign");
        req.setAttribute("sign", sign);
        CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
        //申请人电话
        List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT\n" +
                "\tr.rolecode,u.id\n" +
                "FROM\n" +
                "\tt_s_role r\n" +
                "LEFT JOIN t_s_role_user ru ON r.id = ru.roleid\n" +
                "LEFT JOIN t_s_user u ON ru.userid = u.id\n" +
                "WHERE\n" +
                "\tu.id IN (\n" +
                "\t\tSELECT\n" +
                "\t\t\tid\n" +
                "\t\tFROM\n" +
                "\t\t\tt_s_base_user\n" +
                "\t\tWHERE\n" +
                "\t\t\tusername = '" + cbsEquipmentApplyEntity.getCreateBy() + "'\n" +
                "\t)");
        List<String> mobilePhone = new ArrayList<String>();
        if (forJdbc.get(0).get("rolecode").equals(StaticValue.RULE_CODE_THIRDPARTY_ENGINEER) || forJdbc.get(0).get("rolecode").equals(StaticValue.RULE_CODE_AREA_ENGINEER)) {
            mobilePhone = systemService.findListbySql("select cellphone from zy_engineer where ts_base_user_id='" + forJdbc.get(0).get("id") + "'");
        } else {
            mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
        }
        //获取所属单位信息
        List<String> shortname = systemService.findListbySql("SELECT\n" +
                "\tdp.shortname\n" +
                "FROM\n" +
                "\tt_s_base_user bu\n" +
                "LEFT JOIN t_s_user_org uo ON uo.user_id = bu.ID\n" +
                "LEFT JOIN t_s_depart dp on dp.ID = uo.org_id \n" +
                "WHERE bu.id='" + forJdbc.get(0).get("id") + "'");
        if (shortname.size() != 0) {
            req.setAttribute("shortname", shortname.get(0));
        }
        List<ZyEquipmentSpareEntity> sn = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", cbsEquipmentApplyEntity.getSn());
        if (sn.size() != 0) {
            req.setAttribute("spareId", sn.get(0).getId());
        }
        List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailHql = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.id='" + id + "'");
        List<CbsFaultEquipmentEntity> cbsFaultEquipmentList = systemService.findHql("from CbsFaultEquipmentEntity where applyId='" + id + "'");
        List<String> errorList = systemService.findListbySql("select id from cbs_equipment_error_log where CBS_EQUIPMENT_APPLY_ID='" + id + "'");
        if (errorList.size() != 0) {
            req.setAttribute("code", 1);
        }
        req.setAttribute("cbsFaultEquipmentList", cbsFaultEquipmentList);
        List<TSType> tSTypeHql = systemService.findHql("from TSType where TSTypegroup.id='4028ab036126e7490161274d05280001'");
        CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, cbsEquipmentApplyEntity.getServiceId());
        List<TSTerritory> tSTerritoryHql = systemService.findHql("from TSTerritory where territoryLevel='1'");
        //List<TSTerritory> hql = systemService.findHql ( "from TSTerritory where territoryLevel='2'" );
        List<CbsDeliverEquipmentEntity> cbsDelinerEquipmentHql = systemService.findHql("from CbsDeliverEquipmentEntity where sn='" + cbsEquipmentApplyEntity.getSn() + "'");
        List<CbsHandleLogEntity> cbsHandleLogHql = systemService.findHql("from CbsHandleLogEntity where logType=1 and businessId='" + id + "'order by createDate desc");
        /*if(cbsEquipmentApplyEntity.getWarehouseId()!=null){
			CbsWarehouseEntity cbsWarehouse = systemService.getEntity(CbsWarehouseEntity.class, cbsEquipmentApplyEntity.getWarehouseId());
			req.setAttribute("cbsWarehouse",cbsWarehouse);
		}*/
        //获取发货信息
        List<CbsDelinerEntity> cbsDelinerHql = systemService.findHql("from CbsDelinerEntity where equipmentApplyId.id='" + id + "'");
        List list = new ArrayList();
        if (cbsDelinerHql.size() != 0) {
            if ("1".equals(cbsDelinerHql.get(0).getIsHb())) {
                List<CbsDelinerEntity> hql = systemService.findHql("from CbsDelinerEntity where spaceNumber like '%" + cbsDelinerHql.get(0).getSpaceNumber() + "/%' or spaceNumber like '%/" + cbsDelinerHql.get(0).getSpaceNumber() + "%'");
                List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentHql = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + hql.get(0).getId() + "'");
                list.add(cbsDeliverEquipmentHql);
            } else {
                for (int i = 0; i < cbsDelinerHql.size(); i++) {
                    List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentHql = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsDelinerHql.get(i).getId() + "'");
                    list.add(cbsDeliverEquipmentHql);
                }
            }
            req.setAttribute("list", list);
        }
        // 获取备件申请单相关联的附件
        List<ZyFileLogEntity> fileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "'");
        req.setAttribute("fileList", fileList);
        /*List<ZyFileLogEntity> fileList = new ArrayList<ZyFileLogEntity>();
        String fileId = cbsEquipmentApplyEntity.getFileId();
        if (fileId != null) {
            String[] fileIdSplit = fileId.split(",");
            for (int i = 0; i < fileIdSplit.length; i++) {
                fileList.add((ZyFileLogEntity) systemService.getEntity(ZyFileLogEntity.class, fileIdSplit[i]));
            }
            req.setAttribute("fileList", fileList);
        }*/
        List<TSType> TSTypeList = systemService.findHql("from TSType where TSTypegroup.typegroupname='申请理由'");
        req.setAttribute("TSTypeList", TSTypeList);
        // req.setAttribute("hql",hql);
        req.setAttribute("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
        req.setAttribute("cbsEquipmentApplyDetailHql", cbsEquipmentApplyDetailHql);
        req.setAttribute("tSTypeHql", tSTypeHql);
        req.setAttribute("cbsService", cbsServiceEntity);
        req.setAttribute("tSTerritoryHql", tSTerritoryHql);
        req.setAttribute("cbsDelinerEquipmentHql", cbsDelinerEquipmentHql);
        req.setAttribute("cbsHandleLogHql", cbsHandleLogHql);
        req.setAttribute("mobilePhone", mobilePhone);
        return new ModelAndView("com/zybk/cbsequipmentapply/spareApplyDetail");
    }

    @ResponseBody
    @RequestMapping(params = "getCbsEquipmentById")
    public AjaxJson getCbsEquipmentById(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        String id = req.getParameter("id");
        List<CbsEquipmentApplyDetailEntity> cbsEquipList = null;
        if (StringUtil.isNotEmpty(id)) {
            //根据备件申请单id获取备件申请理由以及是否自提
            String sql = "select apply_reason, zt from cbs_equipment_apply where id = '" + id + "'";
            List<Map<String, Object>> s = systemService.findForJdbc(sql);
            if (s.size() > 0) {
                map.put("cbsEquipmentApply", s.get(0));
            }
            //根据备件申请单获取备件申请详情
            cbsEquipList = cbsEquipmentApplyService.getAllCbsEqipmentByEquipmentId(id);
            map.put("cbsEquipList", cbsEquipList);
        }
        ajaxJson.setAttributes(map);

        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "getCbsEquipmentDetailById")
    public AjaxJson getCbsEquipmentDetailById(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        CbsEquipmentApplyDetailEntity cbsEquip = null;
        if (StringUtil.isNotEmpty(id)) {
            cbsEquip = cbsEquipmentApplyService.getAllCbsEqipmentByDetailId(id);
            if (StringUtil.isNotEmpty(cbsEquip)) {
                ajaxJson.setObj(cbsEquip);
                ajaxJson.setSuccess(true);
            } else {
                ajaxJson.setSuccess(false);
            }
        }

        return ajaxJson;
    }

    /**
     * APP端修改备件信息，只是修改页面的信息，
     * 不更新数据库，当提交备件申请时，才更新数据库
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "updateEquipmentDetailById")
    public AjaxJson updateEquipmentDetailById(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        String id = req.getParameter("id");
        String bjlx = req.getParameter("bjlx");
        String bjh = req.getParameter("bjh");
        String num = req.getParameter("num");
        String appler = req.getParameter("appler");
        if (StringUtil.isNotEmpty(id)) {
            CbsEquipmentApplyDetailEntity cbsEquip = systemService.get(CbsEquipmentApplyDetailEntity.class, id);
            if (StringUtil.isNotEmpty(cbsEquip)) {
//                ZyEquipmentTypeEntity zyEquipmentTypeEntity = systemService.findUniqueByProperty(ZyEquipmentTypeEntity.class, "typeDesc", bjlx);
//                ZyEsItemEntity zyEsItem = systemService.findUniqueByProperty(ZyEsItemEntity.class, "item", bjh);
//                if (StringUtil.isNotEmpty(cbsEquip)) {
//                    if (StringUtil.isNotEmpty(zyEquipmentTypeEntity)) {
//                        cbsEquip.setTypeId(zyEquipmentTypeEntity);
//                    }
//                    if (StringUtil.isNotEmpty(zyEsItem)) {
//                        cbsEquip.setItemId(zyEsItem);
//                    }
//                    cbsEquip.setTypeDes(bjlx);
//                    cbsEquip.setItem(bjh);
//                    cbsEquip.setTotal(Integer.parseInt(num));
//                    cbsEquip.setApplyLayer(Integer.parseInt(appler));
//                    systemService.saveOrUpdate(cbsEquip);
//                }
                map.put("type", "1");
            }

            map.put("bjlx", bjlx);
            map.put("bjh", bjh);
            map.put("num", num);
            map.put("appler", appler);
        }
        ajaxJson.setAttributes(map);
        ajaxJson.setMsg("修改成功");
        return ajaxJson;
    }

    /**
     * APP端工程师删除备件,后修改为只逻辑删除，并不是真的删除
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "deleteEquipmentDetailById")
    public AjaxJson deleteEquipmentDetailById(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setSuccess(true);
        String id = req.getParameter("id");
//        if (StringUtil.isNotEmpty(id)) {
//            int i = systemService.updateBySqlString("DELETE FROM cbs_equipment_apply_detail WHERE id='" + id + "'");
//            if (i > 0) {
//                ajaxJson.setSuccess(true);
//            }
//        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "updateSo")
    public AjaxJson updateSo(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        String so = req.getParameter("so");
        if (StringUtil.isNotEmpty(id)&&StringUtil.isNotEmpty(so)) {
            //获取备件关联的服务单id 和code
            List<Map<String, Object>> serviceIdList = systemService.findForJdbc("SELECT s.id, s.`code`,s.so FROM cbs_service s LEFT JOIN cbs_equipment_apply eq ON s.id = eq.service_id WHERE eq.id = '" + id + "'");
            if (serviceIdList.size() > 0) {
                String serviceId = serviceIdList.get(0).get("id").toString(); //服务单id
                String code = serviceIdList.get(0).get("code").toString(); //服务单code
                //修改服务单下，所有返件的so
                systemService.updateBySqlString("update cbs_return_equipment set SO_CODE = '" + so + "' where CR_CODE = '" + code + "'");
                //修改服务单下，所有发货单的so
                systemService.updateBySqlString("update cbs_deliver set so_code = '" + so + "' where CR_CODE = '" + code + "'");
                //修改服务单so（即备件的so）
                int i = systemService.updateBySqlString("update cbs_service set so = '" + so + "' where id = '" + serviceId + "'");

                if (i > 0) {
                    ajaxJson.setSuccess(true);
                }

                //加入日志
                CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
                cbsHandleLog.setBusinessId(id);
                cbsHandleLog.setLogType(1);
                if (StringUtil.isNotEmpty(serviceIdList.get(0).get("so"))) {
                    cbsHandleLog.setDescription("SO从" + serviceIdList.get(0).get("so") + "修改为" + so + "");
                } else {
                    cbsHandleLog.setDescription("SO修改为" + so + "");
                }
                systemService.save(cbsHandleLog);
            }
        }

        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "updateSr")
    public AjaxJson updateSr(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        String sr = req.getParameter("sr");
        ajaxJson.setSuccess(false);
        if (StringUtil.isNotEmpty(sr) && StringUtil.isNotEmpty(id)) {
            //获取备件关联的服务单id 和code
            List<Map<String, Object>> serviceIdList = systemService.findForJdbc("SELECT s.id, s.`code`,s.sr FROM cbs_service s LEFT JOIN cbs_equipment_apply eq ON s.id = eq.service_id WHERE eq.id = '" + id + "'");
            if (serviceIdList.size() > 0) {
                String serviceId = serviceIdList.get(0).get("id").toString(); //服务单id
                String code = serviceIdList.get(0).get("code").toString(); //服务单code
                //修改服务单下，所有返件的so
                systemService.updateBySqlString("update cbs_return_equipment set sr_code = '" + sr + "' where CR_CODE = '" + code + "'");
                //修改服务单下，所有发货单的so
                systemService.updateBySqlString("update cbs_deliver set sr_code = '" + sr + "' where CR_CODE = '" + code + "'");
                //修改服务单so（即备件的so）
                int i = systemService.updateBySqlString("update cbs_service set sr = '" + sr + "' where id = '" + serviceId + "'");

                if (i > 0) {
                    ajaxJson.setSuccess(true);
                }

                //加入日志
                CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
                cbsHandleLog.setBusinessId(id);
                cbsHandleLog.setLogType(1);
                if (StringUtil.isNotEmpty(serviceIdList.get(0).get("sr"))) {
                    cbsHandleLog.setDescription("SR从" + serviceIdList.get(0).get("sr") + "修改为" + sr + "");
                } else {
                    cbsHandleLog.setDescription("SR修改为" + sr + "");
                }
                systemService.save(cbsHandleLog);
            }
        }
        return ajaxJson;
    }

    //当前日期转化为MMdd字符转
    public String getDateStr(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMdd");
        String dateStr = df.format(date);
        return dateStr;
    }


    /**
     * 根据备件id，检查备件是否已经被操作
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "inspectionResult")
    public AjaxJson inspectionResult(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            CbsEquipmentApplyEntity cbsEquipmentApply = cbsEquipmentApplyService.getEntity(CbsEquipmentApplyEntity.class, id);
            if (StringUtil.isNotEmpty(cbsEquipmentApply) && cbsEquipmentApply.getStatus() == 1) {
                ajaxJson.setSuccess(true);
            } else {
                ajaxJson.setSuccess(false);
            }
        } else {
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }
}
